# -*- coding:utf-8 -*-
import json
import time
from datetime import datetime
import os


# 日志输出
class MyLog:
    __LOG_PATH__ = "log/"

    def __init__(self, filename):
        self.object = open(self.__LOG_PATH__ + filename, "w")

    def write(self, str):
        self.object.write("[%s]....%s\n" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), str))
        self.object.flush()


config = json.load(open('config.json', 'r'))


def my_size(size, index=0):
    DI = ["B", "KB", "MB", "GB"]
    if size < 1000:
        return str(size) + DI[index]
    else:
        return my_size(float(size / 1000), index + 1)


def get_random_str(len):
    import random
    import string
    temp = ''
    while len:
        temp += random.choice(string.ascii_letters)
        len -= 1
    return temp


# 每秒输出时间 伪多线程
class MyTimer:
    def __init__(self, differ=1):
        self.start = 0
        self.differ = differ
        self.filesize = 0

    def get(self, filesize, total):
        if self.start == 0:
            self.start = datetime.now()
            self.filesize = filesize
            return None
        elif (datetime.now() - self.start).seconds >= self.differ:
            self.start = datetime.now()
            speed = my_size(filesize - self.filesize) + "/" + str(self.differ) + "s"
            try:
                process = str('%.2f%%' % (float(filesize) / float(total) * 100))
            except ZeroDivisionError:
                process = "0%"
            self.filesize = filesize
            return speed + '\t' + process


def return_true(info=None):
    return {
        "return": True,
        "info": info
    }


def return_false(info=None):
    return {
        "return": False,
        "info": info
    }


def check():
    try:
        FILE_LIST = [
            'my_protocols/__init__.py',
            'my_protocols/cmd.py',
            'my_protocols/config.py',
            'my_protocols/download.py',
            'my_protocols/upload.py',
            'orm/__init__.py',
            'orm/fst.py',
            'orm/model.py',
            "API.py",
            "config.json",
            "main.py",
            "sqlite3.db"
        ]
        for each in FILE_LIST:
            if os.path.exists(each):
                print each + '......' + 'OK!'
            else:
                print each + 'No Such File!'
                return False

        print 'File Checking Completed!'
        print 'Upload......port: ' + str(config['upload']['port']) + ',token:' + str(config['upload']['token'])
        print 'Download......port: ' + str(config['download']['port']) + ',token:' + str(config['download']['token'])
        print 'Command......port: ' + str(config['command']['port'])
        print 'Mongodb......host: ' + str(config['mongodb']['host']) + ',port:' + str(config['mongodb']['port'])
    except Exception as err:
        print str(err)
        return False
    return True
